<?php
apf_require_controller('HrAbstract');
apf_require_class('Bll_Hr_OutInterface');
class Login_InController extends HrAbstractController {

    private $bll;
    private $data;//post参数
    //上次访问的url
    private $keep = '';


    public function handle_request() {
        $status = false;
        $oauth = APF::get_instance()->get_config('oauth_info');
        //配置了oauth 则用oauth登陆，其他走老的登陆方式
        if ($oauth) {
            $status = $this->handle_request_new($oauth);
        } else {
            $status = $this->handle_request_old();
        }
        if($status) {
            return "Login_In";
        }
    }
    /**
     * 使用oauth 认证登陆
     * **/
    public function handle_request_new($outh) {
        if(isset($_GET['back']) && $_GET['back']) {
            $_SESSION['oauth_use_backurl'] = base64_decode($_GET['back']);
        }
        $info = $this->login_with_oauth($outh['client_id'], $outh['client_secret'], $outh['oauth_url']);
        if(!$info){
            echo "<script>alert('Oauth登录失败，请重试，或与IT联系');</script>";
            $this->response->redirect($url,false,false);exit;
        }
        $info = json_decode($info,true);
        extract($info);
        /*检查用户是否注册，未注册，则继续获取详细信息*/
        $info = $this->get_info_from_ldap($access_token, $outh['oauth_url']);
        if(!$info){
            echo "<script>alert('域信息获取失败，请与IT联系！');</script>";
            $this->response->redirect($url,false,false);exit;
        }
        //使用登陆前的url
        $this->keep = $_SESSION['oauth_use_backurl'];
        unset($_SESSION['oauth_use_backurl']);
        $info = json_decode($info,true);
        $this->get_bll();
        $this->check_login_by_oauth($info['staff_no']);
        return false;
    }

    /**
     * 直接连接域名服务器验证用户信息
     *
     * **/
    public function handle_request_old() {
        if(isset($_POST) and count($_POST)>0){
            $this->data = $this->request->get_parameters();
        }
        if(isset($_GET['back']) && $_GET['back']) {
            $this->keep = base64_decode($_GET['back']);
        }
        $this->get_bll();
        $this->is_login();
        return true;
    }

    private function is_login(){
        $data = $this->data;
        if(isset($data['user_name']) && isset($data['user_psw'])){
            //提交认证
            if(trim($data['user_name'])=='' || trim($data['user_psw'])==''){
                //登录未空
                $this->request->set_attribute('login_msg','用户名和密码不能为空');
            }
            else{
                $this->check_login();
            }

        }
    }

    private function check_login(){
        //进行认证
        $data = $this->data;
        $check = $this->login($data['user_name'], $data['user_psw']);
        if(!$check){
            $this->request->set_attribute('login_msg','用户名或密码错误');
        }
        else{
            //跳转到～登陆前的页面
            $url = "http://".$_SERVER['HTTP_HOST'].'/';
            if($this->keep && preg_match('/'.$_SERVER['HTTP_HOST'].'/',$this->keep)) {
                $url = $this->keep;
            }
            $this->response->redirect($url,false,false);
        }
    }

    /**
     * 用户登录
     */
    public function login($user_name,$user_psw){
        $info = Login_Ldap::get_instance($user_name, $user_psw);
        if($info->get_bind()){
            //登录成功
            $user_ldap = $info->getinfo();

            $bll = new Bll_Hr_OutInterface();
            $user_info = $bll->get_user_base_info($user_ldap['code'],1);
            //TODO session 保存用户信息,过期时间？
            $this->session_act();
            $_SESSION['user_id'] = $user_info['user_id'];
            $_SESSION['email'] = $user_info['office_mail'];
            $_SESSION['code'] = $user_info['user_code'];
            $_SESSION['name'] = $user_info['user_name'];
            $_SESSION['office_mail'] = $user_info['office_mail'];
            $_SESSION['user_code'] = $user_info['user_code'];
            $_SESSION['user_name'] = $user_info['user_name'];
            $_SESSION['department_id'] = $user_info['department_id'];
            $_SESSION['enter_date'] = $user_info['enter_date'];
            $_SESSION['city_name'] = $user_info['city_name'];

            $this->bll->logs('login', $user_info['user_id']);
            return $user_info;
        }
        return false;
    }

    /**
     * Oauth 认证方式
     * @param $code 员工号
     * **/
    private function check_login_by_oauth($code){
        //进行认证
        $data = $this->data;
        $check = $this->login_by_oauth($code);
        $url = "http://".$_SERVER['HTTP_HOST'].'/';
        if(!$check){
            echo "<script>alert('没有对应的员工信息');</script>";
            $this->response->redirect($url,false,false);
        }
        else{
            //跳转到～登陆前的页面
            if($this->keep && preg_match('/'.$_SERVER['HTTP_HOST'].'/',$this->keep)) {
                $url = $this->keep;
            }
            $this->response->redirect($url,false,false);
        }
    }

    /**
     * 用户登录
     */
    public function login_by_oauth($code){
        $result = array();
        if($code){
            //登录成功
            $user_info = $this->bll->get_user_info($code);
            if(empty($user_info)) {
                return $result;
            }
            //TODO session 保存用户信息,过期时间？
            $this->session_act();
            $_SESSION['user_id'] = $user_info['user_id'];
            $_SESSION['email'] = $user_info['email'];
            $_SESSION['code'] = $user_info['code'];
            $_SESSION['user_code'] = $user_info['code'];
            $_SESSION['user_name'] = $user_info['name'];
            $_SESSION['name'] = $user_info['name'];
            $_SESSION['english_name'] =$user_info['english_name'];
            $_SESSION['department_id'] = $user_info['department_id'];
            $_SESSION['enter_date'] = $user_info['enter_date'];
            $_SESSION['city_name'] = $user_info['city_name'];

            apf_require_class("Bll_Attendance_UserInfo");
            $bll = new Bll_Attendance_UserInfo;
            $role  = $bll->get_user_role($user_info['user_id']);
            $_SESSION['role_id'] = $role[$user_info['user_id']]['role_id'];
            $_SESSION['role_name'] = $role[$user_info['user_id']]['role_name'];

            $this->bll->logs('login', $user_info['user_id']);
            return $user_info;
        }
        return $result;
    }

   /**
    * 用户身份认证，
    * 成功则返回用户域账户名和访问令牌
    * oauth
    */
    function login_with_oauth($client_id, $client_secret, $oauth_url){
        if(isset($_REQUEST['code']) && $_REQUEST['code']){
            /*2、用临时令牌，申请访问令牌*/
            $data = array(
                "client_id"=>$client_id,
                "client_secret"=>$client_secret,
                "grant_type"=>'authorization_code',/*默认*/
                "code"=>$_REQUEST['code'],/*临时令牌*/
            );

            header("HTTP/1.1 302 Found");
            header("Location: " . $oauth_url.'/token.php?'.http_build_query($data));
            exit();

        }
        if(isset($_REQUEST['access_token']) && $_REQUEST['access_token']){
            /*3、用AccessToken,获取info*/
            $access_token = $_REQUEST['access_token'];

            $data = array(
                    "oauth_token"=>$access_token,/*只要一个$access_token，是不是很危险？？*/
            );
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $oauth_url."/resource.php");
            curl_setopt($ch, CURLOPT_POST, TRUE);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            $info = curl_exec($ch);
            if($info) return $info;
            else return false;
            exit();
        }
        /*1、获取临时令牌RequestToken*/
        header("HTTP/1.1 302 Found");
        $array = array(
                "client_id"=>$client_id,
                "response_type"=>"code"/*默认*/
        );
        header("Location: " . $oauth_url.'/authorize.php?'.http_build_query($array));
        exit;
    }

    /**
     * 用户注册流程，
     * 用访问令牌到oauth获取用户详细信息
     */
    function get_info_from_ldap($access_token, $oauth_url){
        $data = array(
                "oauth_token"=>$access_token,
                "getinfo"=>true,
        );
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $oauth_url."/resource.php");
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $info = curl_exec($ch);
        if($info) return $info;
        else return false;
    }

    private function get_bll(){
        apf_require_class('Bll_Login_User');
        $bll = new Bll_Login_User();
        $this->bll = $bll;
    }

}